package com.baic.ibase.service.mqtt;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baic.ibase.service.devices.DeviceService;
import com.baic.ibase.service.mqtt.handler.MqttMessageHandlerStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.regex.Pattern;


@Slf4j
@Service
public class ReceiverMessageHandler implements MessageHandler {


    @Autowired
    private MqttMessageHandlerStrategy mqttMessageHandlerStrategy;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        Object payload = message.getPayload();
        MessageHeaders headers = message.getHeaders();

        String receivedTopic = Objects.requireNonNull(headers.get(MqttHeaders.RECEIVED_TOPIC)).toString();
        String receivedQos = Objects.requireNonNull(headers.get(MqttHeaders.RECEIVED_QOS)).toString();
        String receivedRetained = Objects.requireNonNull(headers.get(MqttHeaders.RECEIVED_RETAINED)).toString();
        String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();

        if (!receivedTopic.contains("$SYS")) {
            log.info("receivedTopic: {}, receivedQos: {}, receivedRetained: {}, timestamp: {}, payload: {}",
                    receivedTopic, receivedQos, receivedRetained, timestamp, payload);
        }
        if (receivedTopic.contains("/ibase-device/")) {
            mqttMessageHandlerStrategy.handle(receivedTopic, JSONObject.parseObject(payload.toString()));
        }

    }
}
